/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
  //如果root为空，或是p、q中的其中一个，返回root
  if (!root || root === p || root === q) return root

  //对左子树进行dfs：寻找p、q，把结果赋值给left
  const left = lowestCommonAncestor(root.left, p, q)
  //对右子树进行dfs：寻找p、q，把结果赋值给right
  const right = lowestCommonAncestor(root.right, p, q)

  //如果left、right均非空，说明找到了LCA，返回root
  if (left && right) return root
  //left、right其中一个非空，说明p、q在该侧子树，返回该侧子树
  return left || right
};